package com.TeacherInfoServer.listener;

import com.TeacherInfoServer.exception.DepartmentNameNotExistDetailException;
import com.TeacherInfoServer.exception.JobNumberRepeatedDetailException;
import com.TeacherInfoServer.exception.TypeInfoNotExistException;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.pojo.excelImport.TeacherExcel;
import com.TeacherInfoServer.common.service.CommentService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.TeacherInfoServer.utils.ExcelFormatDateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Data
@Slf4j
@Component
public class TeacherListener implements ReadListener<TeacherExcel> {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    Validator validator;
    @Autowired
    CommentService commentService;
    @Autowired
    TypeInfoService typeInfoService;


    private final List<Teacher> teacherList = new ArrayList<>();
    private final List<Teacher> updateList = new ArrayList<>();
    private final List<Teacher> addList = new ArrayList<>();
    private final List<String> teacherIdList = new ArrayList<>();
    private Integer record;
    @Override
    public void invoke(TeacherExcel teacherExcel, AnalysisContext analysisContext) {
        Set<ConstraintViolation<TeacherExcel>> violations = validator.validate(teacherExcel);
        if (violations.isEmpty()) {
            if (!teacherIdList.contains(teacherExcel.getTeacherId())){
                if(commentService.findDepartmentByName(teacherExcel.getDepartment())==null){
                    throw new DepartmentNameNotExistDetailException("表中教研室："+teacherExcel.getDepartment()+"不存在");
                }
                if (typeInfoService.getOneId("职称类型",teacherExcel.getJobTitle())==null){
                    throw new TypeInfoNotExistException("表中职称："+teacherExcel.getJobTitle()+"不存在");
                }
                if (typeInfoService.getOneId("学历类型",teacherExcel.getEducated())==null){
                    throw new TypeInfoNotExistException("表中学历："+teacherExcel.getEducated()+"不存在");
                }
                if (typeInfoService.getOneId("学位类型",teacherExcel.getDegree())==null){
                    throw new TypeInfoNotExistException("表中学位："+teacherExcel.getDegree()+"不存在");
                }
                if(typeInfoService.getOneId("民族类型",teacherExcel.getEthnic())==null){
                    throw new TypeInfoNotExistException("表中民族："+teacherExcel.getEthnic()+"不存在");
                }
                if(typeInfoService.getOneId("学院类型",teacherExcel.getCollege())==null){
                    throw new TypeInfoNotExistException("表中学院："+teacherExcel.getCollege()+"不存在");
                }
                String formattedBirthDate = ExcelFormatDateUtil.formatDate(teacherExcel.getBirthDate());
                if (formattedBirthDate == null){
                    throw new IllegalArgumentException("日期格式无效: " + teacherExcel.getBirthDate());
                }
                Teacher teacher = new Teacher(null,
                        teacherExcel.getTeacherId(),
                        teacherExcel.getTeacherName(),
                        teacherExcel.getGender(),
                        formattedBirthDate,
                        teacherExcel.getIdCardNumber(),
                        typeInfoService.getOneId("职称类型",teacherExcel.getJobTitle()),
                        commentService.findDepartmentByName(teacherExcel.getDepartment()).getId(),
                        typeInfoService.getOneId("学位类型",teacherExcel.getDegree()),
                        typeInfoService.getOneId("学历类型",teacherExcel.getEducated()),
                        typeInfoService.getOneId("民族类型",teacherExcel.getEthnic()),
                        typeInfoService.getOneId("学院类型",teacherExcel.getCollege()),
                        teacherExcel.getAge(),1);
                teacherList.add(teacher);
                teacherIdList.add(teacherExcel.getTeacherId());

            }else {
                throw new JobNumberRepeatedDetailException("表中教师工号："+teacherExcel.getTeacherId()+"重复");
            }
        }else {
            String errorMessage = violations.iterator().next().getMessage();
            throw new ConstraintViolationException(errorMessage, violations);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
       List<Teacher> teachers = teacherService.list();
       teacherList.forEach(teacher -> {
           Optional<Teacher> dbTeacher = teachers.stream()
                   .filter(t -> t.getTeacherId().equals(teacher.getTeacherId()))
                   .findFirst();
          dbTeacher.ifPresent(t -> {
              teacher.setId(t.getId());
              updateList.add(teacher);
          });
           if(dbTeacher.isEmpty()){
               addList.add(teacher);

           }

       });
        List<Teacher> mergedList = Stream.concat(updateList.stream(),addList.stream()).collect(Collectors.toList());
        teacherService.saveOrUpdateBatch(mergedList);
        setRecord(mergedList.size());
        initList();
    }

    public void initList(){
        teacherList.clear();
        updateList.clear();
        addList.clear();
        teacherIdList.clear();
    }


}
